package com.web;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.annotations.UpdateProvider;

import com.entity.PageBean;
import com.entity.Product;
import com.entity.ProductBigCategory;
import com.service.ProductService;
import com.service.ProductmService;
import com.service.impl.ProductmServiceImpl;

import net.sf.json.JSONObject;

@WebServlet("/ProductmServlet")
public class ProductmServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		
		String op=request.getParameter("op");
		
		
		if ("queryAllProducts".equals(op)) {
			queryAllProducts(request,response);
		}else if ("delpro".equals(op)) {
			delProById(request,response);
		}else if ("addpro".equals(op)) {
			addProduct(request,response);
		}else if ("updatepro".equals(op)) {
			  UpdatePro(request,response);
		}else if ("findProById".equals(op)) {
			findProById(request,response);
		}else if ("prefindProById".equals(op)) {
			prefindProById(request,response);
		}else if ("findproBycategory".equals(op)) {
			findproBycategory(request,response);
		}else if ("getproList".equals(op)) {
			getproList(request,response);
		}
		
	}

	private void getproList(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		ProductmService pms=new ProductmServiceImpl();
		try {
			List<ProductBigCategory> queryAllCategory = pms.queryAllCategory();
			request.setAttribute("proCate",queryAllCategory);
			request.getRequestDispatcher("/manage/product-add.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void findproBycategory(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String category = request.getParameter("category");
		String pageCode=request.getParameter("currpage");
		ProductmService pms=new ProductmServiceImpl();
		PageBean<Product> pb=new PageBean();
		int currentCode;
		if (pageCode!=null&&!"".equals(pageCode)) {
		 currentCode=Integer.parseInt(pageCode);
		 pb.setPageCode(currentCode);
		}else {
			currentCode=1;
			pb.setPageCode(currentCode);
		}
		try {
			List<Product> pro = pms.findproBycategory(category, currentCode);
			pb.setTotalCount(pms.queryCountByCategory(category));
			pb.setBeanList(pro);
			
			response.getWriter().write(JSONObject.fromObject(pb).toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private void prefindProById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pid=request.getParameter("pid");
		ProductmService pms=new ProductmServiceImpl();
		try {
			Product product= pms.findProById(pid);
			request.setAttribute("pro", product);
			request.getRequestDispatcher("/product-view.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void findProById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pid=request.getParameter("pid");
		ProductmService pms=new ProductmServiceImpl();
		try {
			Product product= pms.findProById(pid);
			List<ProductBigCategory> queryAllCategory = pms.queryAllCategory();
			request.setAttribute("pro", product);
			request.setAttribute("proCate",queryAllCategory);
			request.getRequestDispatcher("/manage/product-modify.jsp").forward(request, response);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void UpdatePro(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Product p=new Product();
		ProductmService pms=new ProductmServiceImpl();
		try {
			BeanUtils.populate(p, request.getParameterMap());
			int updatePro = pms.updatePro(p);
			if (updatePro>0) {
				response.sendRedirect(request.getContextPath()+"/manage/manage-result.jsp");
			}else {
				response.sendRedirect("error.jsp");
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	private void addProduct(HttpServletRequest request, HttpServletResponse response) throws IOException {
		DiskFileItemFactory dis=new DiskFileItemFactory();
		ServletFileUpload sfu=new ServletFileUpload(dis);
		sfu.setFileSizeMax(1024*1024*10);//限制上传大小为10M
		Product p=new Product();
		try {
			List<FileItem> fItems = sfu.parseRequest(request);
			for (FileItem f : fItems) {
				if (f.isFormField()) {
					String pid=UUID.randomUUID().toString();
					p.setPid(pid);
					if (f.getFieldName().equals("productName")) {
						p.setPname(f.getString("UTF-8"));
					}
					if (f.getFieldName().equals("productDetail")) {
						p.setDescription(f.getString("utf-8"));
					}
					if (f.getFieldName().equals("parentId")) {
						p.setP_spid(f.getString("utf-8"));
					}
					if (f.getFieldName().equals("productPrice")) {
						
						int price=Integer.parseInt(f.getString("utf-8"));
						p.setPrice(price);
					}
					if (f.getFieldName().equals("productNumber")) {
						int pnum=Integer.parseInt(f.getString("utf-8"));
						p.setPnum(pnum);
					}
				}else {
					
					String dirpath=request.getServletContext().getRealPath(request.getServletContext().getInitParameter("uploadImage"));
					String imguuid=UUID.randomUUID().toString();
					String upname=f.getName();
					File uploadpath=new File(dirpath+"/"+imguuid+"_"+upname);
					try {
						f.write(uploadpath);
						p.setImgurl(dirpath+"/"+imguuid+"_"+upname);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		ProductmService pms=new ProductmServiceImpl();
		try {
			int res = pms.addProduct(p);
			if (res>0) {
				response.sendRedirect("manage/manage-result.jsp");
			}else {
				response.sendRedirect("error.jsp");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void delProById(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pid=request.getParameter("pid");
		ProductmService pms=new ProductmServiceImpl();
		try {
			int affline = pms.delproById(pid);
			if (affline>0) {
				response.sendRedirect(request.getContextPath()+"/manage/product.jsp");
			}else {
				response.sendRedirect("error.jsp");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

	private void queryAllProducts(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		ProductmService pms=new ProductmServiceImpl();
		PageBean<Product> pb=new PageBean();
		String pageCode=request.getParameter("currpage");
		int currentCode;
		if (pageCode!=null&&!"".equals(pageCode)) {
			
		 currentCode=Integer.parseInt(pageCode);
		 pb.setPageCode(currentCode);
		}else {
			currentCode=1;
			pb.setPageCode(currentCode);
		}
		try {
			List<Product> allproducts = pms.queryAllProduct(currentCode);
			pb.setTotalCount(pms.queryCount());
			
			pb.setBeanList(allproducts);
			response.getWriter().write(JSONObject.fromObject(pb).toString());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
